<?php
namespace App\Http\Controllers\Wx;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Yunpian\Sdk\YunpianClient;
use App\Repos\StaffRepo;
use App\Services\RedisService;
use App\Models\Depart;
use App\Models\Position;
use App\Models\Category;
use App\Models\DiancanNotice;
use EasyWeChat;
use Log;

class HomeController extends Controller
{
    
    // 返回openid    
    public function getOpenid(Request $request)
    {
        $rs['status'] = false;
        $code = trim($request->code);
        $mini = EasyWeChat::miniProgram(); // 小程序
        $result = $mini->auth->session($code); // $code 为wx.login里的code
        if(!array_key_exists('openid', $result)) {
            $rs['msg'] = $result['errmsg'];
            return response()->json($rs);
        }
        $rs['status'] = true;
        $rs['openid']      = $result['openid'];
        $rs['session_key'] = $result['session_key'];
        return response()->json($rs);
    }

    /**
     * 获取微信用户信息，主要是unionid
     */
    public function getWxUser(Request $request)
    {
        $rs['status'] = false;      
        $session     = $request->session_key;
        $iv          = $request->iv;
        $encryptData = $request->encryptData;
        $app         = EasyWeChat::miniProgram(); // 小程序
        $decryptedData = $app->encryptor->decryptData($session, $iv, $encryptData);
        if($decryptedData) {
            $rs['status'] = true;
            $rs['data'] = $decryptedData;            
            return response()->json($rs);
        }
        return response()->json($rs);
    }
   
    // 小程序验证身份获取token
    public function getToken(Request $request)
    {
       

        // 短信验证码
        $mobile        = $request->mobile; 
        $validate_code = $request->validate_code;   
        $smsCode       = RedisService::get('hainan:sms:'.$mobile);
        if($smsCode!=$validate_code) {
            $rs['msg'] = '短信验证码错误';
            return response()->json($rs);
        }
        
        $rs['status'] = true;
        

        $user = StaffRepo::find(['mobile'=>$request->mobile]);
        if($user) {
            $rs['data']['token']   = $user->token;
            $rs['data']['user_id'] = $user->id;
            return response()->json($rs);
        }

        $data = array_only($request->all(),['longitude','latitude','avatar','nickname','name','mobile','depart_id','position_id','unionid','small_openid']);
      
        $user =StaffRepo::create($data);
        $rs['data']['token']   = $user->token;
        $rs['data']['user_id'] = $user->id;
        return response()->json($rs);   
    }

    public function pushSms(Request $request)
    {
        $rs['status'] = true;
        $mobile = trim($request->mobile);
        $code   = RedisService::get('hainan:sms:'.$mobile);

        if($code) {
            $rs['data'] = $code;
            return response()->json($rs);
        }
        $apikey = 'c9c3eb615bfb5f75c059f22f79089714';
        $code   = mt_rand(1000,9999);
       
        //初始化client,apikey作为所有请求的默认值
        $clnt = YunpianClient::create($apikey);
        
        $text = '【东湖分院事务处理中心】您的验证码是'.$code;
        $param = [YunpianClient::MOBILE => $mobile,YunpianClient::TEXT => $text];
        $r = $clnt->sms()->single_send($param); 
        //dd($r);       
        if($r->isSucc()){           
            RedisService::set('hainan:sms:'.$mobile,$code);
            $rs['data'] = $code;
            return response()->json($rs);

        } else {
            //var_dump($r->msg());die;
            Log::info($r->msg());
            $rs['status'] = true;
            $rs['msg'] = '发送失败';
            return response()->json($rs);
            
        }
    }

    // 部门
    public function getDepart(Request $request)
    {
        $rs['status'] = true;
        $list = Depart::select(['id','name'])->get();
        $rs['data'] = $list;
        return response()->json($rs);
    }

    // 岗位
    public function getPosition(Request $request)
    {
        $rs['status'] = true;
        $list = Position::select(['id','name'])->get();
        $rs['data'] = $list;
        return response()->json($rs);   
    }

    /**
     * 故障类别
     */
    public function getCategory(Request $request)
    {
        $rs['status'] = true;
        $list = Category::select(['id','name'])->get();
        $rs['data'] = $list;
        return response()->json($rs);
    }

    public function upload(Request $request)
    {
        $rs['status'] = true;
        $folder       = 'uploads/'.date('Ymd');
        
        if ($request->isMethod('post')) {
            $file = $request->file('file');

            // 文件是否上传成功
            if ($file->isValid()) {
                
                $path = '/'.$file->store($folder);                    
                
                $rs['data'] = $path;
                return response()->json($rs);
            }

        }
        return response()->json(['rs' => false, 'msg' => '不是正确请求方式']);
    }


    
   


    
}
